# https://www.r-graph-gallery.com/168-load-a-shape-file-into-r
# https://www.worldfullofdata.com/r-tutorial-plot-maps-shapefiles/
# https://www.r-bloggers.com/2018/04/visualizing-geo-spatial-data-with-sf-and-plotly/
# https://www.r-bloggers.com/2020/11/visualizing-geospatial-data-in-r-part-1-finding-loading-and-cleaning-data/
#install.packages("rgeos",repos='http://cran.us.r-project.org') # needed for tidy, install before rgdal
#install.packages("rgdal",repos='http://cran.us.r-project.org') # on linux need to install gdal binaries separately, for Windows and Mac, these are included in the R package
#install.packages("maptools",repos='http://cran.us.r-project.org')
#install.packages("rnaturalearth",repos='http://cran.us.r-project.org')
#install.packages('rworldmap',dependencies=TRUE,repos='http://cran.us.r-project.org') 
#install.packages("broom",repos='http://cran.us.r-project.org')
library(rgdal)
library(rgeos)
library(ggplot2)
library(broom)
library(maptools)
library(rnaturalearth)
library(rworldmap)
# Download the shapefile. (note that I store it in a folder called mapdata. You have to change that if needed.)
#download.file("http://thematicmapping.org/downloads/TM_WORLD_BORDERS_SIMPL-0.3.zip" , destfile="./mapdata/world_shape_file.zip")
# You now have it in your current working directory, have a look!

# Unzip this file. You can do it with R (as below), or clicking on the object you downloaded.
#system("unzip ./mapdata/world_shape_file.zip -d mapdata")
#  -- > You now have 4 files. One of these files is a .shp file! (TM_WORLD_BORDERS_SIMPL-0.3.shp)

# Read shape file with maptools

shapefile <- readShapeSpatial('../mapdata/TM_WORLD_BORDERS_SIMPL-0.3.shp')

# Read ldi data
LDI <- read.csv(file="./LDI.csv",
                 header=TRUE,sep=",")
#
sPDF <-
  joinCountryData2Map(LDI,
                      joinCode="ISO3",
                      nameJoinColumn="ISO3")

## Plot language diversity index
par(mai=c(0,0,0.2,0),xaxs="i",yaxs="i")
mapDevice(device="svg",
          file="LDI_Africa.svg",
          width=7)

#View(sPDF@data)
mapParams <-
  mapCountryData( sPDF,
		  mapRegion="africa",
                  nameColumnToPlot="LDI",
                  mapTitle='',
                  oceanCol='lightblue',
                  missingCountryCol='grey',
                  addLegend=FALSE )
do.call( addMapLegend,
         c(mapParams,
	   legendMar=43,
	   legendLabels="all",
           legendWidth=0.5,
           legendShrink = 0.7,
           horizontal = FALSE))
dev.off()

